<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;


use App\Models\CompanyScale;

class CompanyScaleController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        if(!$this->user->can('viewCompanyScale')) abort(405);
        
        $scales = CompanyScale::paginate(20);
        return view('admin.enterprise.companyscale.index')->with('scales', $scales);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        if(!$this->user->can('editCompanyScale')) abort(405);
        
        return view('admin.enterprise.companyscale.add')->with('blademod', 'add');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        if(!$this->user->can('editCompanyScale')) abort(405);
        
        //表单验证
        $this->validate($request, [
            'name' => 'required|max:100',
        ]);
        $id = $request->get('id', 0);
        $name = $request->get('name');
        if ($id >0){
            $scale = CompanyScale::find($id);
            $scale->name = $name;
            $scale->save();
        }
        else{
            CompanyScale::firstOrCreate(['name' => $name]);
        }

        return redirect("admin/enterprise/company_scale");

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        if(!$this->user->can('viewCompanyScale')) abort(405);
        
        $scale = CompanyScale::find($id);
        return view('admin.enterprise.companyscale.add')->with('scale', $scale)->with('blademod', 'edit');
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        if(!$this->user->can('deleteCompanyScale')) abort(405);
        
        $scale = CompanyScale::find($id);
        if ($scale->delete())
            return  Response::json(array('status'=>'success','msg'=>'规模 ['. $scale->name .'] 删除成功! '));
        else
            return  Response::json(array('status'=>'error','msg'=>'删除失败'));
    }
}
